package com.aier.admin_new.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aier.classes.common.InviteRequestUtil;
import com.aier.classes.entity.ClassParent;
import com.aier.classes.entity.ClassStudent;
import com.aier.classes.entity.Classes;
import com.aier.classes.service.IClassService;
import com.aier.classes.service.IClassUserService;
import com.aier.common.common.Constant;
import com.aier.common.common.ICommonDAO;
import com.aier.common.common.ImageUtil;
import com.aier.common.common.SendSchoolPhoneMessage;
import com.aier.common.common.SystemConfigStatic;
import com.aier.common.service.ISysPhoneMessageService;
import com.aier.school.entity.School;
import com.aier.school.entity.SchoolMessage;
import com.aier.school.entity.SchoolTeacher;
import com.aier.school.service.ISchoolService;
import com.aier.school.service.ISchoolTeacherService;
import com.aier.user.service.IHsConBookService;
import com.aier.user.service.IUserBuyService;


@Scope("prototype")
@Component("bulletinAction")
public class BulletinAction  extends AdminNewBaseAction{
	
	/**
     * 学校和班级公告（新版）
     */
    private static final long serialVersionUID = 1L;

    @Resource(name = "hsConBookService")
    private IHsConBookService hsConBookService;
    @Resource(name = "classUserService")
    private IClassUserService classUserService;
    @Resource(name = "classService")
    private IClassService classService;
    @Resource(name = "schoolService")
    private ISchoolService schoolService;
    @Resource(name = "schoolTeacherService")
    private ISchoolTeacherService schoolTeacherService;
    @Resource(name = "sysPhoneMessageService")
    private ISysPhoneMessageService sysPhoneMessageService;
    @Resource(name = "userBuyService")
    private IUserBuyService userBuyService;

    private int s; // 错误码
    private int page; // 页数
    private int page_size; // 每页的记录数
    private int page_count; // 总页数
    private int count; // 总数

    private List<SchoolMessage> schoolMessageList;// 公告列表

    private Integer sid; // 学校id
    private Long cid; // 班级id
    private Long tid; // 教师id
    private File[] image; // 图片
    private String content; // 公告内容
    private String title;   // 公告标题
    private String imageName; // 图片名称
    private Boolean isSendPhone=false; // 是否发送短信
    private Boolean isAllTeacher = false; // 是否全体教师
    private Boolean isAllClass = false; // 是否全体师生
    private Boolean isAllParent = false; // 班级全体家长

    private String[] photoName; // 上传图片的名称或路径
    
    private Integer mesCount; // 学校剩余短信数量
    private Long mid; // 公告id
    
    private String unreadingList;  // 公告未读列表
    private List<ClassStudent> readingList; // 公告已读列表
    private Integer peoCount; // 公告短信发送的人数
    private Short type;  // 身份（1教师2家长）
    private Long uid;  // 用户id
    
    @Override
    public String execute() {
        // 学校管理员
        if (sid != null) {
            mesCount = schoolTeacherService.searchSchoolTeacherById(tid).getMesCount();
            s = 1;
            return "SUCCESS_SCHOOL";
        }
        // 班级管理员
        if (cid != null) {
            mesCount = classService.searchClassById(cid).getMesCount();
            s = 1;
            return "SUCCESS_CLASS";
        }
        s = 1;
        return SUCCESS;
    }
    
    /**
     * 查询公告
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String searchSchoolMessageList() {
        s = 1;
        if (page <= 0) {
            page = 1;
        }
        if (page_size <= 0) {
            page_size = Constant.num_10;
        }
        try {
            Map<String, Object> map = null;
            if (type == 1) {
                if (sid != null) {
                    // 学校管理员
                    map = schoolService.searchSchoolMessageListNew(page, page_size,
                            sid);
                } else {
                    // 班级教师
                    map = schoolService
                            .searchClassMessageListNew(page, page_size, cid);
                }
            } else {
                // 家长
                map = schoolService
                        .searchParentMessageListNew(page, page_size, cid);
            }
            if (null != map) {
                schoolMessageList = (List<SchoolMessage>) map
                        .get(ICommonDAO.OBJ_LIST);
                page_count = (Integer) map.get(ICommonDAO.PAGE_COUNT);
                count = (Integer) map.get(ICommonDAO.COUNT);
                page = (Integer) map.get(ICommonDAO.PAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            s = 0;
        }
        return SUCCESS;
    }

    // 发布公告前提示发送短信条数
    public String searchMessageCount() {
        s = 1;
        List<SchoolTeacher> stList = new ArrayList<SchoolTeacher>();
        List<ClassParent> cpList = new ArrayList<ClassParent>();
        
        title = InviteRequestUtil.getFilterMessage(title);
        content = InviteRequestUtil.getFilterMessage(content);
        content = title +":"+content;
                
        if (isAllTeacher) {// 全体教师（学校公告）
            stList = schoolTeacherService
                    .searchSchoolTeacherListSid_account(sid);
        } 
        if (isAllClass) {// 全体师生（学校公告）
            cpList = classUserService
                    .searchClassParentListSid_account(sid);
            stList = schoolTeacherService
                    .searchSchoolTeacherListSid_account(sid);
        }
        if (isAllParent) {// 某班级的全体家长（班级公告）
            List<Long> cidList = new ArrayList<Long>();
            cidList.add(cid);
            cpList = classUserService
                    .searchClassParentListCidList_account(cidList);
            Classes cl = classService.searchClassById(cid);
            content = content + "【" + cl.getCname() + "】";
        }
        
        // 判断公告的长度,计算每条评语需要发送几条短信
        content = content + "【爱儿360】";
        
        int size = 1;
        
        if (content.length() > Constant.num_70) {
            int len = content.length();
            size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
        }
        
        mesCount = (cpList.size() + stList.size())*size;
        peoCount = cpList.size() + stList.size();
        
        School school = userBuyService.searchSchoolMessageCountSid(sid);
        if (school.getMethod() == 2) {
            int c = 0;
            if (cid != null) {
                c = classService.searchClassById(cid).getMesCount();
            } else {
                c = schoolTeacherService.searchSchoolTeacherById(tid).getMesCount();
            }
            // 短信条数不足
            if (c < mesCount) {
                s = 0;
            }
        }
        
        return SUCCESS;
    }
    
    // 发布公告
    public String addSchoolMessage() {
        List<List<String>> userPhoneList = new ArrayList<List<String>>();
        List<SchoolTeacher> stList = new ArrayList<SchoolTeacher>();
        List<ClassParent> cpList = new ArrayList<ClassParent>();
        List<ClassStudent> ctList = new ArrayList<ClassStudent>();
        s = 1;
        
        if (cid == null) {
            // 学校公告
            SchoolTeacher st = schoolTeacherService.searchSchoolTeacherById(tid);
            if (st.getIsadmin() == (short) 1) {
                short type = 0; // 学校公告类型
                if (isAllTeacher) {// 全体教师
                    stList = schoolTeacherService
                            .searchSchoolTeacherListSid_account(sid);
                    type = 2;
                } 
                if (isAllClass) {// 全体师生
                    cpList = classUserService
                            .searchClassParentListSid_account(sid);
                    stList = schoolTeacherService
                            .searchSchoolTeacherListSid_account(sid);
                    ctList = classUserService.searchClassStudentListBySid(sid);
                    type = 0;
                }
                st.getTname();                
                Long mid = schoolService.insertSchoolMessageNew(sid, tid, title, content,imageName,type,stList.size()+ctList.size());
                
                if (isSendPhone) {// 是否发送短信
                    for (SchoolTeacher sTeacher : stList) {
                        List<String> upList = new ArrayList<String>();
                        upList.add(sTeacher.getAccount());
                        upList.add(sTeacher.getUid().toString());
                        upList.add("1");
                        userPhoneList.add(upList);
                    }
                    for (ClassParent sParent : cpList) {
                        List<String> upList = new ArrayList<String>();
                        upList.add(sParent.getAccount());
                        upList.add(sParent.getUid().toString());
                        upList.add("0");
                        userPhoneList.add(upList);
                    }   
                    // 判断公告的长度,计算每条公告需要发送几条短信
                    title = InviteRequestUtil.getFilterMessage(title);
                    content = InviteRequestUtil.getFilterMessage(content);
                    content = title +":"+content + "【爱儿360】";
                    
                    int size = 1;
                    
                    if (content.length() > Constant.num_70) {
                        int len = content.length();
                        size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
                    }
                    
                    new SendSchoolPhoneMessage(userPhoneList, content, sid,
                            sysPhoneMessageService,1,mid,size,tid).start();
                    
                }

            } else {
                s = 0;
            }
            mesCount = schoolTeacherService.searchSchoolTeacherById(tid).getMesCount();
        } else {
            // 班级公告
            ctList = classUserService.searchAllClassStudentList(cid);
            Long mid = schoolService.insertClassMessageNew(cid, tid, title, content, imageName,ctList.size());
            
            if (isSendPhone) {// 是否发送短信
                List<Long> cidList = new ArrayList<Long>();
                cidList.add(cid);
                cpList = classUserService
                        .searchClassParentListCidList_account(cidList);
                stList = schoolTeacherService
                        .searchSchoolTeacherListCidList_account(cidList);
                for (SchoolTeacher sTeacher : stList) {
                    List<String> upList = new ArrayList<String>();
                    upList.add(sTeacher.getAccount());
                    upList.add(sTeacher.getUid().toString());
                    upList.add("1");
                    userPhoneList.add(upList);
                }
                for (ClassParent sParent : cpList) {
                    List<String> upList = new ArrayList<String>();
                    upList.add(sParent.getAccount());
                    upList.add(sParent.getUid().toString());
                    upList.add("0");
                    userPhoneList.add(upList);
                }    
                // 判断公告的长度,计算每条公告需要发送几条短信
                title = InviteRequestUtil.getFilterMessage(title);
                content = InviteRequestUtil.getFilterMessage(content);
                Classes cl = classService.searchClassById(cid);
                content = title +":"+content + "【" + cl.getCname() + "】" + "【爱儿360】";
                
                int size = 1;
                
                if (content.length() > Constant.num_70) {
                    int len = content.length();
                    size = ((double)len/(double)Constant.num_67)>(len/Constant.num_67) ? len/Constant.num_67+1 : len/Constant.num_67;
                }
                
                new SendSchoolPhoneMessage(userPhoneList, content, sid,
                        sysPhoneMessageService,1,mid,size,tid).start();
            }
            mesCount = classService.searchClassById(cid).getMesCount();
        }
        
        return SUCCESS;

    }
    
    /**
     * 删除公告图片
     * @return
     */
    public String deleteImage() {
        File fo = new File(SystemConfigStatic.homework_upload_url + "origin/" +imageName);
        if (fo.exists()) {
            fo.delete();
        }
        File fs = new File(SystemConfigStatic.homework_upload_url + "small/" +imageName);
        if (fs.exists()) {
            fs.delete();
        }
        File fb = new File(SystemConfigStatic.homework_upload_url + "big/" +imageName);
        if (fb.exists()) {
            fb.delete();
        }
        s = 1;
        return SUCCESS;
    }

    /**
     * 查看公告详情，修改阅读量（班级公告需要保存阅读记录）
     * @return
     */
    public String searchDetail() {
        s = schoolService.insertMessageReading(mid,tid,uid);
        if(s==1){
        	schoolMessageList = new ArrayList<SchoolMessage>();
        	SchoolMessage e=schoolService.searchMessagebyMid(mid);     
    		schoolMessageList.add(e);   		
        }else{
        	s=0;
        }
        return SUCCESS;
    }
    
    // 获取公告阅读/未阅读列表
    public String searchReadingList() {
    	
        unreadingList = schoolService.searchUnReadingList(mid);
        
        readingList = classUserService.searchCSByCondition(mid);
        
        s = 1;
        return SUCCESS;
    }
    
    /**
     * 删除公告
     * @return
     */
    public String deleteMessage() {
        s = hsConBookService.deleteMessage(mid);
        return SUCCESS;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setPage_size(int page_size) {
        this.page_size = page_size;
    }

    public int getS() {
        return s;
    }

    public void setHsConBookService(IHsConBookService hsConBookService) {
        this.hsConBookService = hsConBookService;
    }

    public void setCid(Long cid) {
        this.cid = cid;
    }

    public void setTid(Long tid) {
        this.tid = tid;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public void setClassUserService(IClassUserService classUserService) {
        this.classUserService = classUserService;
    }

    public void setImage(File[] image) {
        this.image = image;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public void setClassService(IClassService classService) {
        this.classService = classService;
    }

    public Long getTid() {
        return tid;
    }

    public Long getCid() {
        return cid;
    }

    public void setSchoolService(ISchoolService schoolService) {
        this.schoolService = schoolService;
    }

    public Integer getSid() {
        return sid;
    }

    public void setSid(Integer sid) {
        this.sid = sid;
    }

    public List<SchoolMessage> getSchoolMessageList() {
        return schoolMessageList;
    }

    public void setSchoolTeacherService(
            ISchoolTeacherService schoolTeacherService) {
        this.schoolTeacherService = schoolTeacherService;
    }

    public int getPage_count() {
        return page_count;
    }

    public int getCount() {
        return count;
    }

    public int getPage() {
        return page;
    }

    public void setPhotoName(String[] photoName) {
        this.photoName = photoName;
    }

    public void setSysPhoneMessageService(
            ISysPhoneMessageService sysPhoneMessageService) {
        this.sysPhoneMessageService = sysPhoneMessageService;
    }

    public void setIsSendPhone(Boolean isSendPhone) {
        this.isSendPhone = isSendPhone;
    }

    public void setIsAllClass(Boolean isAllClass) {
        this.isAllClass = isAllClass;
    }

    public void setIsAllTeacher(Boolean isAllTeacher) {
        this.isAllTeacher = isAllTeacher;
    }

    public void setUserBuyService(IUserBuyService userBuyService) {
        this.userBuyService = userBuyService;
    }

    public Integer getMesCount() {
        return mesCount;
    }

    public void setMid(Long mid) {
        this.mid = mid;
    }

    public void setIsAllParent(Boolean isAllParent) {
        this.isAllParent = isAllParent;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getUnreadingList() {
        return unreadingList;
    }

    public List<ClassStudent> getReadingList() {
        return readingList;
    }

    public Integer getPeoCount() {
        return peoCount;
    }

    public void setType(Short type) {
        this.type = type;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }
	
	
}
